//编辑，详情动态表格
<template>
  <el-dialog
    v-el-drag-dialog="{updataFull, updataDialogWidth}"
    :fullscreen="isfullscreen"
    :width="setDialogWidth('90%')"
    :visible="visible"
    :title="title"
    :append-to-body="true"
    class="segment-list-box"
    @open="open"
    @close="close"
  >
    <!-- 业务基本信息显示 -->
    <biz-info :form-data="rowData" />
    <div class="font-weight-bold pl-20">{{ $t('INTERMEDIATE_NODE') }}</div>
    <el-divider class="m-0 mt-10 mb-10" />
    <div class="text-color text-center">{{ $t('CURRENT_LINK_CHANNEL') }}</div>
    <biz-graphical
      ref="curBizGraphical"
      class="mb-20"
      :biz-channel-list="useSegmentList"
      :cable-data="graphicalCableData"
    />
    <div class="text-color text-center">{{ $t('RESTORE_TO_ORIGINAL') }}</div>
    <biz-graphical
      ref="targetBizGraphical"
      class="mb-20"
      :biz-channel-list="targetSegmentList"
      :cable-data="graphicalCableData"
      operate-type="reduction"
    />
    <!-- 通道信息 -->
    <el-table ref="segmentTable" border :data="channelList" style="width: 100%" size="mini">
      <template slot="empty">
        <NullData />
      </template>
      <el-table-column type="index" :label="$t('SEQUENCE')" :width="resetSize(60)" align="center" />
      <el-table-column
        :label="$t('INTERMEDIATE_NODE')"
        align="center"
        prop="linkInfo"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        prop="nodeNum"
        :label="$t('NODE_NUM')"
        width="100"
        show-overflow-tooltip
      />
      <el-table-column
        :label="$t('FIBER_TOTAL_TIME')"
        width="120"
        prop="cutoverTime"
        align="center"
      >
        <template v-slot="scope">
          {{
            scope.row.cutoverTime > 990000 || 0 > scope.row.cutoverTime
              ? '--'
              : scope.row.cutoverTime
          }}
        </template>
      </el-table-column>
      <el-table-column :label="$t('LINK_LOSS')" width="110" prop="loss" align="center">
        <template v-slot="scope">
          {{
            scope.row.loss > 990000
              ? '--'
              : changeDecimal(scope.row.loss, 3)
          }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        prop="linkLength"
        :label="$t('LESS_LENGTH')"
        width="110"
        show-overflow-tooltip
      />
      <el-table-column :label="$t('TRANSFER_DETAIL')" fixed="right" prop="cutoverList">
        <template v-slot="scope">
          {{ cutoverDesc(scope.row) }}
        </template>
      </el-table-column>
    </el-table>
    <!-- 还原时间选择 -->
    <el-form ref="timeForm" class="mt-20" :model="formData" label-width="110px" :rules="rules">
      <el-form-item :label="$t('REDUCTION_START_TIME')" prop="startTime">
        <el-date-picker
          v-model="formData.startTime"
          popper-class="reduction-time-picker"
          :disabled="disableTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          format="yyyy-MM-dd HH:mm"
          data-format="yyyy-MM-dd HH:mm"
          :picker-options="startPickerOptions"
          style="width: 200px"
          :placeholder="$t('REDUCTION_START_TIME')"
          :clearable="false"
          :default-value="new Date()"
          :default-time="formatDate(new Date(),'HH:mm:ss')"
        />
        <!-- <el-popover width="200" trigger="hover">
          <div class="text-color" v-html="$t('REDUCTION_START_TIME_TIPS')" />
          <i slot="reference" class="iconfont icon-AFSwenhao ml-5" />
        </el-popover> -->
      </el-form-item>
    </el-form>
    <template v-slot:footer>
      <el-button v-if="disableTime" @click="del">{{ $t('CANCEL_REDUCTION') }}</el-button>
      <el-button @click="close">{{ $t('CLOSE') }}</el-button>
      <el-button v-if="!disableTime" type="primary" @click="save">{{ $t('SAVE') }}</el-button>
    </template>
  </el-dialog>
</template>
<script>
  import { mapGetters } from 'vuex'
  import bizOpenApi from '@/api/oen/BizOpenApi'
  import { checkAfs, changeDecimal, formatDate, correctOrder, getDateTime } from '@/utils/common'
  import BizInfo from './components/BizInfo'
  import BizGraphical from '@/components/BizGraphical'
  export default {
    name: 'SegmentDetail',
    components: { BizInfo, BizGraphical },
    props: {
      visible: {
        type: Boolean,
        default: false
      },
      rowData: {
        type: Object,
        default: () => {}
      }
    },
    inject: ['functionName', 'parentVM'],
    data() {
      return {
        formData: {
          startTime: ''
        },
        formatDate: formatDate,
        channelList: [],
        startPickerOptions: {
          disabledDate: time => {
            return time.getTime() < new Date().getTime() - 24 * 60 * 60 * 1000
          }
        },
        disableTime: false,
        changeDecimal: changeDecimal,
        useSegmentList: [],
        targetSegmentList: [],
        graphicalCableData: {}
      }
    },
    computed: {
      ...mapGetters(['dictMap']),
      title() {
        let title = this.$t('INTELLIGENCE_RESTORE')
        if (
          this.rowData.bizChannelList &&
          this.rowData.bizChannelList.some(i => i.bizStatus === 'RETURNING')
        ) {
          title += ' - ' + this.$t('BIZ_STATUS_RETURNING')
        }
        return title
      },
      rules() {
        return {
          startTime: [
            {
              required: true,
              message: this.$t('PLEASE_SELECT') + this.$t('REDUCTION_START_TIME'),
              trigger: 'blur'
            },
            { validator: this.checkeTime, trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      open() {
        this.disableTime = false
        this.formData = this.$options.data().formData
        this.getDetail()
        this.getReductionInfo()
      },
      // 检测时间必须大于当前时间
      checkeTime(rule, value, callback) {
        const ok =
          this.formData.startTime &&
          new Date(this.formData.startTime).getTime() <
          new Date().getTime()
        ok ? callback(new Error(this.$t('RESTORE_TIME_ERROR'))) : callback()
      },
      // 移纤描述
      cutoverDesc(row) {
        const desc = []
        row.cutoverList.forEach((i, index2) => {
          const str = this.$t('PORT_CONNECT_LINK', {
            msg1: i.deviceName,
            msg2: i.port.bizName,
            msg3: i.connPort.bizName
          })
          desc.push(str)
        })
        return desc.join('；') || this.$t('NO_PIPETTING_IS_REQUIRED')
      },
      // 获取详情
      getDetail() {
        // console.log('this.rowData', this.rowData)
        this.channelList = []
        bizOpenApi.initialChannel({ bizId: this.rowData.bizId }).then(res => {
          const useSegmentList = []
          const targetSegmentList = []
          res.forEach(i => {
            // 获取光缆信息
            const nodeList = {}
            i.targetNetworkSegmentList.forEach(j => {
              nodeList[j.startNodeId] = j.startNode
              nodeList[j.endNodeId] = j.endNode
              if (j.cable) {
                this.graphicalCableData[j.cableId] = j.cable
              }
            })
            i.useNetworkSegmentList.forEach(j => {
              nodeList[j.startNodeId] = j.startNode
              nodeList[j.endNodeId] = j.endNode
              if (j.cable) {
                this.graphicalCableData[j.cableId] = j.cable
              }
            })
            i.targetSegmentChannelList = correctOrder(i.targetSegmentChannelList, this.rowData.startNodeId)
            i.linkLength = changeDecimal(i.linkLength, 3, true)
            const linkInfo = []
            const endNodeList = []

            i.targetSegmentChannelList.forEach((j, index) => {
              j.startNode = j.startNode || nodeList[j.startNodeId] || {}
              j.endNode = j.endNode || nodeList[j.endNodeId] || {}
              if (index === 0) {
                linkInfo.push(j.startNode.nodeName)
              }
              linkInfo.push(j.endNode.nodeName)
              endNodeList.push(j.endNodeId)
            })
            i.cutoverList.sort((a, b) => {
              const aIndex = endNodeList.indexOf(a.deviceId)
              const bIndex = endNodeList.indexOf(b.deviceId)
              return aIndex - bIndex
            })
            i.linkInfo = linkInfo.join('-->')
            useSegmentList.push({ segmentList: i.useSegmentChannelList })
            targetSegmentList.push({ segmentList: i.targetSegmentChannelList })
          })
          this.useSegmentList = useSegmentList
          this.targetSegmentList = targetSegmentList
          this.channelList = res || []
          this.$nextTick(() => {
            this.$refs.curBizGraphical && this.$refs.curBizGraphical.formatData()
            this.$refs.targetBizGraphical && this.$refs.targetBizGraphical.formatData()
          })
        })
      },
      // 获取已设置还原信息
      getReductionInfo() {
        bizOpenApi.reductionInfo({ bizId: this.rowData.bizId }).then(res => {
          if (!res) return
          this.disableTime = new Date(res.executeTime).getTime() > new Date().getTime()
          this.formData = {
            startTime: res.executeTime
          }
        })
      },
      async submit() {
        // 判断原通道AFS设备是否可用
        // const checkeAfs = await checkAfs(
        //   {
        //     routeData: {
        //       segmentList: this.channelList[0].targetNetworkSegmentList
        //     },
        //     channelData: this.channelList
        //   },
        //   'INTELLIGENCE_RESTORE'
        // )
        // if (!checkeAfs) return
        bizOpenApi.reductionChannelIdle({ bizId: this.rowData.bizId }).then(res => {
          if (!res) {
            this.$message.error(this.$t('ORIGINAL_LINK_CANNOT_RESTORED'))
            return
          }
          const queryData = {
            bizName: this.rowData.bizName,
            bizId: this.rowData.bizId,
            executeTime: getDateTime(this.formData.startTime),
            functionName: this.parentVM.functionName || this.functionName
          }
          bizOpenApi.reduction(queryData).then(res => {
            this.$message.success(this.$t('REQUEST_SUCCESS'))
            this.close(true)
          })
        })
      },
      save() {
        this.$refs.timeForm.validate(valid => {
          if (!valid) return
          this.$confirm(this.$t('CONFIRM_START_RESTORE'), { type: 'warning' })
            .then(() => {
              this.submit()
            })
            .catch(() => {})
        })
      },
      // 删除还原信息
      del() {
        this.$confirm(this.$t('CONFIRM_DELETE_REDUCTION'), { type: 'warning' })
          .then(() => {
            bizOpenApi.delReduction({
              bizId: this.rowData.bizId,
              functionName: this.parentVM.functionName || this.functionName, // 操作日志需要的参数
              bizName: this.rowData.bizName // 操作日志需要的参数
            }).then(res => {
              this.$message.success(this.$t('REQUEST_SUCCESS'))
              this.formData = {
                startTime: ''
              }
              this.disableTime = false
            })
          })
          .catch(() => {})
      },
      close(data) {
        this.$emit('close', data)
        this.formData = this.$options.data().formData
        this.$nextTick(() => {
          this.$refs.timeForm && this.$refs.timeForm.clearValidate()
        })
      }
    }
  }
</script>
<style lang="scss">
.reduction-time-picker .el-picker-panel__footer .el-button--text {
  display: none;
}
.reduction-time-picker{
  .el-scrollbar:nth-child(3) {
    display: none !important;
  }
  .el-time-spinner {
      text-align: center;
  }
}
</style>
